package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.entities.SimpleCodingSubmission;
import cn.thoughtworks.school.handlers.BusinessException;
import cn.thoughtworks.school.repositories.SimpleCodingQuizSubmissionRepository;
import cn.thoughtworks.school.requestParams.HomeworkSubmissionParam;
import cn.thoughtworks.school.services.SimpleCodingSubmissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

import static cn.thoughtworks.school.services.Utils.readFileToString;

@RestController
@RequestMapping(value = "/api/simpleCodingSubmissions")
public class SimpleCodingSubmissionController {

    private final Logger logger = LoggerFactory.getLogger(StackController.class);
    @Autowired
    private SimpleCodingSubmissionService simpleCodingSubmissionService;

    @Value("${quiz-center-url}")
    private String quizCenterUrl;

    @Autowired
    private SimpleCodingQuizSubmissionRepository simpleCodingQuizSubmissionRepository;


    @PostMapping("")
    public ResponseEntity judgeQuiz(@RequestBody HomeworkSubmissionParam data) throws BusinessException {
        logger.info(String.format("POST %s %s", "/api/v3/homeworkSubmission", data));

        revertStudentSubmission(data);
        SimpleCodingSubmission simpleCodingSubmission = simpleCodingSubmissionService.judgeCodingQuiz(data);

        return new ResponseEntity<>(simpleCodingSubmission, HttpStatus.CREATED);
    }

    private void revertStudentSubmission(HomeworkSubmissionParam data) {
        SimpleCodingSubmission codingSubmission = simpleCodingQuizSubmissionRepository
                .findByUserIdAndAssignmentIdAndAndQuizId(data.getStudentId(),data.getAssignmentId(),data.getQuizId()).orElseGet(SimpleCodingSubmission::new);
        if (Objects.nonNull(codingSubmission.getId())) {
            simpleCodingQuizSubmissionRepository.delete(codingSubmission);
        }
    }

    @GetMapping("users/{userId}/assignments/{assignmentId}/quizzes/{quizId}")
    public ResponseEntity getSubmission(@PathVariable Long userId,
                                        @PathVariable Long assignmentId,
                                        @PathVariable Long quizId) {
        SimpleCodingSubmission codingSubmission = simpleCodingQuizSubmissionRepository
                .findByUserIdAndAssignmentIdAndAndQuizId(userId,assignmentId,quizId).orElseGet(SimpleCodingSubmission::new);
        return new ResponseEntity<>(codingSubmission, HttpStatus.OK);
    }


    @PutMapping("{id}/result/{status}")
    public ResponseEntity updateResult(@PathVariable Long id,
                                       @PathVariable Integer status,
                                       @RequestParam(value = "message") MultipartFile message) throws BusinessException {
        SimpleCodingSubmission codingSubmission = simpleCodingQuizSubmissionRepository.findById(id).orElseThrow(() ->
                new BusinessException("当前记录不存在"));

        String jobMessage = readFileToString(message);
        codingSubmission.setJobMessage(jobMessage);
        codingSubmission.setStatus(status);
        simpleCodingQuizSubmissionRepository.save(codingSubmission);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PutMapping("{id}/status")
    public ResponseEntity updateStatus(@PathVariable Long id,
                                       @RequestParam(value = "message", required = false) MultipartFile message) throws BusinessException, IOException {
        SimpleCodingSubmission codingSubmission = simpleCodingQuizSubmissionRepository.findById(id).orElseThrow(() ->
                new BusinessException("提交不存在"));
        System.out.println(message.getBytes().toString());
        String description = readFileToString(message);
        System.out.println(description);
        codingSubmission.setJobMessage(description);
        simpleCodingQuizSubmissionRepository.save(codingSubmission);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

}
